﻿using System;
using System.Collections.Generic;
using System.IO;

namespace chromium.HTTP.Parser
{
    public class HttpRequest
    {
        private readonly DateTime requestDate = DateTime.Now;
        private string rawUrl;
        private Uri uri;
        private readonly MemoryStream requestStream = new MemoryStream();
        private readonly Dictionary<string, string> headers = new Dictionary<string, string>(StringComparer.CurrentCultureIgnoreCase);

        public DateTime RequestDate
        {
            get { return requestDate; }
        }

        public string Method { get; set; }

        public string RawUrl
        {
            get
            {
                if (!rawUrl.StartsWith("http://", StringComparison.CurrentCultureIgnoreCase))
                {
                    return "https://" + Host + rawUrl;
                }
                return rawUrl;
            }
            set { rawUrl = value; }
        }

        public Uri Uri
        {
            get { return uri ?? (uri = new Uri(RawUrl)); }
        }

        public string Version { get; set; }

        public Dictionary<string, string> Headers
        {
            get { return headers; }
        }

        public int ContentLength
        {
            get { return Convert.ToInt32(headers["Content-Length"]); }
        }

        public MemoryStream RequestStream
        {
            get { return requestStream; }
        }

        public string Host
        {
            get { return headers["host"]; }
        }

        public int ElapsedMs
        {
            get { return (int) (DateTime.Now - requestDate).TotalMilliseconds; }
        }

        public string GetHeader(string name)
        {
            return headers.ContainsKey(name) ? headers[name] : null;
        }
    }
}